package com.pro.api;

import com.alibaba.fastjson.JSON;
import com.pro.VO.UserInfoVo;
import com.pro.bean.UserInfo;
import com.pro.dto.Dto;
import com.pro.service.UserInfoService;
import com.pro.util.dtoUtil.DtoUtil;
import com.pro.util.redisUtil.RedisUtil;
import com.pro.util.tokenUtil.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
/**
 * 记得写注释！！
 * 后台后端接口
 *当前类为UserInfo控制层
 *
 **/
@RestController
@RequestMapping("userInfo")
public class UserInfoController {
    //注入服务层
    @Autowired
    private UserInfoService userInfoService;
    //注入token
    @Autowired
    private TokenUtil tokenUtil;
    //注入Redis数据库
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询表中所有数据
     * **/
    @GetMapping(value = "all")
    public Dto  all(){
        return DtoUtil.returnSuccess(userInfoService.all());
    }

    /***
     * 登陆功能
     *
     * @RequestBody 将前端传来json数据转换为Java对象
     * */
    @PostMapping(value = "login")
    public Dto login(@RequestBody UserInfo userInfo, HttpServletRequest request){
        UserInfo u = userInfoService.login(userInfo.getUserName());
        if(u==null){
            return  DtoUtil.returnError(5000,"没有该用户名");
        }else {
            if(u.getPassword().equals(userInfo.getPassword())){
                String agent = request.getHeader("user-agent");
                UserInfoVo uv = new UserInfoVo();
                try {
                    //tokenUilt类中方法来信息动态生成token
                    String token = tokenUtil.token(agent,userInfo.getUserName());
                    //前端不能存密码，所以设置为空
                    u.setPassword("");
                    //Redis存储前端token动态生成信息
                    redisUtil.setStr(token, JSON.toJSONString(u));

                    uv.setData(u);
                    uv.setToken(token);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //用户成功登陆
                return DtoUtil.returnSuccess(uv);
            }else {
                //进入该方法表示用户密码错误
                return  DtoUtil.returnError(5001,"密码错误");
            }
        }
    }

   //拉黑用户功能
    @PostMapping(value = "userInfoUpdate")
    public Dto userInfoUpdate(@RequestBody UserInfo userInfo){
        return DtoUtil.returnSuccess(userInfoService.userInfoUpdate(userInfo));
    }

    //取消拉黑用户功能
    @GetMapping(value = "cancel")
    public Dto cancel(int id){
        return DtoUtil.returnSuccess(userInfoService.cancel(id));
    }

    //拉黑用户分页
    @GetMapping(value = "page")
    public Dto page(int pageIndex,int size){
            return DtoUtil.returnSuccess(userInfoService.page(pageIndex,size));
        }
}



